package com.hdl.school.utils;

import android.content.SharedPreferences;
import android.util.Log;

import com.alibaba.fastjson.JSON;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 执行android命令
 *
 * @author Yuedong Li
 *
 */
public class SuUtil {

    private static Process process;

    /**
     * 结束进程,执行操作调用即可
     */
    public static void kill(String packageName) {
        initProcess();
        killProcess(packageName);
        close();
    }

    public static void reboot() {
        initProcess();
        if(process!=null) {
            OutputStream out = process.getOutputStream();
            String cmd = "reboot -p\n";
            try {
                out.write(cmd.getBytes());
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        close();
    }

    /**
     * 初始化进程
     */
    private static void initProcess() {
        if (process == null) {
            try {
                process = Runtime.getRuntime().exec("su");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 结束进程
     */
    private static void killProcess(String packageName) {
        if(process!=null) {
            OutputStream out = process.getOutputStream();
            String cmd = "am force-stop " + packageName + " \n";
            try {
                out.write(cmd.getBytes());
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭输出流
     */
    private static void close() {
        if (process != null)
            try {
                process.getOutputStream().close();
                process = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }


}

